import axios from 'axios'
// import Vue from 'vue'
// import utils from '../libs/utils.js'
import { ElMessage } from 'element-plus'

axios.defaults.timeout = 100000 // 设置超时时间
let tokens = JSON.parse(localStorage.getItem('pro__Access-Token'))
axios.interceptors.request.use(
  (config) => {
    // 判断爬虫
    // console.log('window.navigator.webdriver', window.navigator.webdriver)
    if (!window.navigator.webdriver) {
      return config
    }
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

class HTTP {
  /**
   * @description: 提供外部使用的 request 方法，用于接口调用
   * @param {Object}
   * @return {Promise}
   */
  request({ method, url, data, headers }) {
    return new Promise((resolve, reject) => {
      this._request({
        method,
        url,
        data,
        headers,
        resolve,
        reject
      })
    })
  }

  /**
   * @description: 封装使用 axios 库的 _request 方法
   * @param {Object}
   */
  _request({
    method = 'GET',
    url,
    data = {},
    // tokens.value?tokens.value:
    headers = {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Blade-Auth': 'd2lzaW5mbzgyNDM0NA=='
    },
    resolve,
    reject
  }) {
    let params = {}
    if (method.toUpperCase() === 'GET') {
      // GET 请求使用 params
      params = data
    }
    if (headers && data) {
      console.log(data)
      const contentType = headers['Content-Type']
      if (contentType === 'application/x-www-form-urlencoded') {
        params = new URLSearchParams()
        for (let key in data) {
          params.append(key, data[key])
        }
        data = {}
      } else if (contentType === 'multipart/form-data') {
        let formData = new FormData()
        for (let key in data) {
          formData.append(key, data[key])
        }
        data = formData
      }
    }
    axios({
      baseURL: '', 
      url,
      method,
      data,
      params,
      headers: this._mergeHeaders(this._getHeaders(), headers)
    })
      .then((response) => {
        const { data } = response
        // console.log(data)
        if (data && data.code === 200) {
          // status 为 200 表示接口成功，后台接口约定俗成
          resolve(data)
        } else {
          if (data.code === 401) {
            ElMessage.error({
              message: 'token已过期',
              duration: 1500,
              onClose: () => {
                // window.location.replace(
                //   'https://detest.jxt.zj.gov.cn:8889/enduser/sp/sso/testplugin_jwt215?enterpriseId=test&defaultAdapter=testZhengWuZheJiang1'
                // )
              }
            })
          } else {
            reject(data)
            ElMessage.error(data.message)
          }
        }
      })
      .catch((error) => {
        const { response } = error
        reject(error)
        if (response) {
          console.log('response', response)
          if (response.status === 401) {
            ElMessage.error({
              message: 'token已过期',
              duration: 1500,
              onClose: () => {}
            })
          }
          if (response.code === 500) {
            ElMessage.error(response.data.extra.exceptionMessage)
          } else {
            ElMessage.error(response.data.message)
          }
        } else {
          // utils.showHttpErrorInfo(error, this)
          // reject(error)
        }
      })
  }

  /**
   * @description: 获取 headers 字段
   * @return {Object}
   */
  _getHeaders() {
    const jsessionId =
      (localStorage.getItem('user') &&
        JSON.parse(localStorage.getItem('user')).token) ||
      'd2lzaW5mbzgyNDM0NA=='
    if (jsessionId) {
      return {
        'Blade-Auth': jsessionId
      }
    } else {
      return {}
    }
  }

  /**
   * @description: 合并 headers 参数
   * @param {Object} defaultHeaders
   * @param {Object} headers
   */
  _mergeHeaders(defaultHeaders, headers) {
    return Object.assign({}, defaultHeaders, headers)
  }
}

export default HTTP
